package com.example.serialportdemo;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.BRMicro.NETLH_E;
import com.BRMicro.PARA_TABLE;
import com.example.serialportdemo.service.SerialPortService;

import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {
    public static NETLH_E netlh_e=NETLH_E.getInstance();
    private PARA_TABLE para_table=new PARA_TABLE();
    private int[] CmdReadParaTable_ErrFlag=new int[1];

    private ScanKeyManager scanKeyManager;
    /*是否是输入状态（输入时扫码监听不拦截）*/
    private boolean isInput = false;

    private IMyAidlInterface myAidlInterface=new IMyAidlInterface.Default();
    private ServiceConnection connection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myAidlInterface=IMyAidlInterface.Stub.asInterface(service);
        };

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    private  void makeOpenByRunOnUiThread(final Button btn)//更新UI
    {
        MainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                btn.setBackgroundDrawable(getResources().getDrawable(R.mipmap.open));
            }
        });
    }
    private void makeCloseByRunOnUiThread(final Button btn)//更新UI
    {
        MainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                btn.setBackgroundDrawable(getResources().getDrawable(R.mipmap.close));
            }
        });
    }
    //1
    //温度显示控制
    private Button ControlTemp, ControlTempAdd, ControlTempReduce,getControlTemp;
    private TextView ShowTemp_tv,ShowTemp_tv_1;
    private EditText ControlTemp_et,scan;
    private Button test,reset;
    //2
    //开门
    private Button cabinetOpen1, cabinetOpen2, cabinetOpen3, cabinetOpen4;

    //注册、登录
    private Button register,login;
    /**
     * 主程序
     * @param savedInstanceState
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //让虚拟键一直不显示
//        Window window = getWindow();
//        WindowManager.LayoutParams params = window.getAttributes();
//        params.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE;
//        window.setAttributes(params);

        startService(new Intent(MainActivity.this, SerialPortService.class));
        bindService(new Intent(MainActivity.this, SerialPortService.class), connection, Context.BIND_AUTO_CREATE);

        InitForm();
        InitonClick();

        Timer timer= new Timer();
        timer.schedule(timerTask_1,0,3000);//获取温度
        timer.schedule(timerTask_2,200,3000);//警告信息
        timer.schedule(timerTask_3,500,1000);//判断关门
        InitUSB();
        onKeyBoardListener();
        //拦截扫码器回调,获取扫码内容
        scanKeyManager = new ScanKeyManager(new ScanKeyManager.OnScanValueListener() {
            @Override
            public void onScanValue(String value) {
                Log.d("ScanValue", value);
            }
        });
    }

    public void InitUSB(){
        netlh_e.ConfigCommParameterUDisk(0xffffffff,0xffffffff);//开启USB
        netlh_e.CmdReadParaTable(para_table,CmdReadParaTable_ErrFlag);
        Log.d("USB测试","version:"+para_table.cSWVersion);
    }

    /**
     * 初始化控件
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public void InitForm() {
        //温度显示控制
        ControlTemp = findViewById(R.id.btnControlTemp);
        getControlTemp=findViewById(R.id.btngetSetTemp);
        ControlTempAdd = findViewById(R.id.btnControlTemp_2);
        ControlTempReduce = findViewById(R.id.btnControlTemp_1);
        ControlTemp_et = findViewById(R.id.etControlTemp);
        ShowTemp_tv = findViewById(R.id.tvShowTemp);
        ShowTemp_tv_1=findViewById(R.id.tvShowTemp_1);

        //开关门
        cabinetOpen1 = findViewById(R.id.btn_cabinetOpen1);
        cabinetOpen2 = findViewById(R.id.btn_cabinetOpen2);
        cabinetOpen3 = findViewById(R.id.btn_cabinetOpen3);
        cabinetOpen4 = findViewById(R.id.btn_cabinetOpen4);
        test=findViewById(R.id.btn_test);
        reset=findViewById(R.id.btn_reset);

        //注册、登录
        register=findViewById(R.id.btn_register);
        login=findViewById(R.id.btn_login);

        scan=findViewById(R.id.barcode);
    }


    /**
     * 初始化点击事件
     */
    public void InitonClick() {
        /**
         * 获取设定温度
         */
        getControlTemp.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                try {
                    float[] f=myAidlInterface.getTargetTemperature();
                    ShowTemp_tv_1.setText(f[0]+"");
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });
        /**
         * 温度设置
         */
        ControlTemp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ((ControlTemp_et.getText().toString().length() > 0) && (Float.parseFloat(ControlTemp_et.getText().toString()) > 1.9) && (Float.parseFloat(ControlTemp_et.getText().toString()) < 8.1)) {
                    try {
                        myAidlInterface.setTargetTemperature(Float.parseFloat(ControlTemp_et.getText().toString()));
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        /**
         * 温度+
         */
        ControlTempAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                float temp=Float.parseFloat(ControlTemp_et.getText().toString()) + 1;
                if(temp>8.0){
                    temp=(float) 8.0;
                }
                else if(temp<2.0){
                    temp=(float) 2.0;
                }
                ControlTemp_et.setText(temp+"");
            }
        });
        /**
         * 温度-
         */
        ControlTempReduce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                float temp=Float.parseFloat(ControlTemp_et.getText().toString()) - 1;
                if(temp>8.0){
                    temp=(float) 8.0;
                }
                else if(temp<2.0){
                    temp=(float) 2.0;
                }
                ControlTemp_et.setText(temp+"");
            }
        });

        /**
         * 开门
         */
        cabinetOpen1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    myAidlInterface.unlockCabinet(1);
                    makeOpenByRunOnUiThread(cabinetOpen1);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });
        cabinetOpen2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    myAidlInterface.unlockCabinet(2);
                    makeOpenByRunOnUiThread(cabinetOpen2);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });
        cabinetOpen3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    myAidlInterface.unlockCabinet(3);
                    makeOpenByRunOnUiThread(cabinetOpen3);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });
        cabinetOpen4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    myAidlInterface.unlockCabinet(4);
                    makeOpenByRunOnUiThread(cabinetOpen4);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });

        test.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if(myAidlInterface.switchTestMode()){
                        Toast.makeText(MainActivity.this, "进入测试模式", Toast.LENGTH_SHORT).show();
                    }
                    startActivity(new Intent(MainActivity.this,TestActivity.class));
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });

        reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if(myAidlInterface.resetSystem()) {
                        Toast.makeText(MainActivity.this, "复位成功", Toast.LENGTH_SHORT).show();
                    }
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });

        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(netlh_e!=null){
                    Intent intent=new Intent(MainActivity.this, RegisterActivity.class);
                    startActivity(intent);
                }
            }
        });

        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(netlh_e!=null){
                    Intent intent=new Intent(MainActivity.this, LoginActivity.class);
                    startActivity(intent);
                }
            }
        });
    }
    TimerTask timerTask_1 = new TimerTask() {
        @Override
        public void run() {//获取温度
            if(handler!=null){
                Message msg=Message.obtain();
                try {
                    float[] f=myAidlInterface.getTemperature();
                    msg.obj=f;
                    msg.what=1;
                    handler.sendMessage(msg);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }
    };
    TimerTask timerTask_2 = new TimerTask() {
        @Override
        public void run() {//警告信息
            if(handler!=null){
                Message msg=Message.obtain();
                try {
                    msg.obj=myAidlInterface.getWarnInfo();
                    msg.what=2;
                    handler.sendMessage(msg);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }
    };
    TimerTask timerTask_3 = new TimerTask() {
        @Override
        public void run() {//判断关门
            if(handler!=null){
                Message msg=Message.obtain();
                try {
                    boolean[] b=myAidlInterface.isCabinetUnlock();
                    msg.obj=b;
                    msg.what=3;
                    handler.sendMessage(msg);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }
    };
    public Handler handler=new Handler(){
        @Override
        public void handleMessage(android.os.Message msg) {
            if(msg.obj!=null){
                switch (msg.what){
                    case 1: float[] temperature=(float[])msg.obj;
                        ShowTemp_tv.setText(temperature[0]+"");
                        break;//更新温度
                    case 2:
                        boolean[] myWarnInfo=(boolean[])msg.obj;
//                        if(myWarnInfo[0]=true){
//                            Toast.makeText(MainActivity.this, "低温警告", Toast.LENGTH_LONG).show();
//                        }
//                        if(myWarnInfo[1]=true){
//                            Toast.makeText(MainActivity.this, "高温警告", Toast.LENGTH_LONG).show();
//                        }
//                        if(myWarnInfo[2]=true){
//                            Toast.makeText(MainActivity.this, "环境高温警告", Toast.LENGTH_LONG).show();
//                        }
//                        if(myWarnInfo[3]=true){
//                            Toast.makeText(MainActivity.this, "显示温度传感器故障警告", Toast.LENGTH_LONG).show();
//                        }
//                        if(myWarnInfo[4]=true){
//                            Toast.makeText(MainActivity.this, "控制温度传感器故障警告", Toast.LENGTH_LONG).show();
//                        }
//                        if(myWarnInfo[5]=true){
//                            Toast.makeText(MainActivity.this, "环境温度传感器故障警告", Toast.LENGTH_LONG).show();
//                        }
//                        if(myWarnInfo[6]=true){
//                            Toast.makeText(MainActivity.this, "冷凝温度传感器1故障警告", Toast.LENGTH_LONG).show();
//                        }
//                        if(myWarnInfo[7]=true){
//                            Toast.makeText(MainActivity.this, "冷凝温度传感器2故障警告", Toast.LENGTH_LONG).show();
//                        }
//                        if(myWarnInfo[8]=true){
//                            Toast.makeText(MainActivity.this, "制冷系统1故障警告", Toast.LENGTH_LONG).show();
//                        }
//                        if(myWarnInfo[9]=true){
//                            Toast.makeText(MainActivity.this, "制冷系统2故障警告", Toast.LENGTH_LONG).show();
//                        }
//                        if(myWarnInfo[10]=true){
//                            Toast.makeText(MainActivity.this, "冷暖风机1故障警告", Toast.LENGTH_LONG).show();
//                        }
//                        if(myWarnInfo[11]=true){
//                            Toast.makeText(MainActivity.this, "冷暖风机2故障警告", Toast.LENGTH_LONG).show();
//                        }
//                        if(myWarnInfo[12]=true){
//                            Toast.makeText(MainActivity.this, "外部电源输出故障警告", Toast.LENGTH_LONG).show();
//                        }
//                        if(myWarnInfo[13]=true){
//                            Toast.makeText(MainActivity.this, "箱门60分钟未关警告", Toast.LENGTH_LONG).show();
//                        }
                        break;
                    case 3:
                        boolean[] b=(boolean[])msg.obj;
                        if(b[0]==false){
                            makeCloseByRunOnUiThread(cabinetOpen1);
                        }
                        else{
                            makeOpenByRunOnUiThread(cabinetOpen1);
                        }
                        if(b[1]==false){
                            makeCloseByRunOnUiThread(cabinetOpen2);
                        }
                        else{
                            makeOpenByRunOnUiThread(cabinetOpen2);
                        }
                        if(b[2]==false){
                            makeCloseByRunOnUiThread(cabinetOpen3);
                        }
                        else{
                            makeOpenByRunOnUiThread(cabinetOpen3);
                        }
                        if(b[3]==false){
                            makeCloseByRunOnUiThread(cabinetOpen4);
                        }
                        else{
                            makeOpenByRunOnUiThread(cabinetOpen4);
                        }
                        break;//更新柜门
                }
            }
        }
    };


    /*监听键盘事件,除了返回事件都将它拦截,使用我们自定义的拦截器处理该事件*/
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() != KeyEvent.KEYCODE_BACK&& !isInput) {
            scanKeyManager.analysisKeyEvent(event);
            return true;
        }
        return super.dispatchKeyEvent(event);
    }
    //监听软件盘是否弹起
    private void onKeyBoardListener() {
        SoftKeyBoardListener.setListener(this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                Log.e("软键盘", "键盘显示 高度" + height);
                isInput = true;
            }

            @Override
            public void keyBoardHide(int height) {
                Log.e("软键盘", "键盘隐藏 高度" + height);
                isInput = false;
            }
        });
    }
}



